from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import pymysql
import json

# Create your views here.

def helloworld(request):
    return HttpResponse("hahaha")

# def get_menu(request):
#     apps = init_app_data()
#     published_app_data = apps.get('published')
#     response = wrap_json_response(data=published_app_data, code=ReturnCode.SUCCESS)
#     return JsonResponse(data=response, safe=False, status=200)


class DBHelper(object):
    def __init__(self):
        self.connection = pymysql.connect(host="172.17.0.2", user="root", passwd="123", database="movies", charset="utf8")
        self.cursor = self.connection.cursor()

    def insert(self, *params):
        sql = """
        INSERT INTO movies (name, year, style, site, brief_intro, tag, download_url) VALUES ("{}", {}, "{}", "{}", "{}", "{}", "{}");
        """.format(*params)
        print(sql)
        try:
            self.cursor.execute(sql)
            self.connection.commit()
        except Exception as e:
            print("try to execute SQL: {} failed, err info: {}".format(sql, e))

    def query(self, *items):
        ret = []
        sql = """
        SELECT {} from movies;
        """.format(",".join(items))
        print(sql)
        try:
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
        except Exception as e:
            print("query failed, sql: {}, err: {}".format(sql, e))
        for index, val in enumerate(res):
            movie = dict(zip(items, val))
            ret.append(movie)
        return ret

    def query_info(self, name):
        ret = None
        sql = "SELECT name, year, brief_intro from movies where name={}".format(name)
        print(sql)
        try:
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
        except Exception as e:
            print("query failed, sql: {}, err: {}".format(sql, e))

        return res


def movie_list(request):
    db_helper = DBHelper()
    ret = db_helper.query("name", "style", "download_url")
    json_ret = {index: val for index, val in enumerate(json.loads(str(ret).replace('\'', '\"'), encoding="utf8"))}
    print(json_ret)

    return JsonResponse(data=json_ret, safe=False, status=200)
